import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, logout, getInfo } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const name = ref('')
  const avatar = ref('')
  const roles = ref([])
  const userInfo = ref(null)

  const setToken = (value) => {
    token.value = value
    localStorage.setItem('token', value)
  }

  const clearToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }

  const setUserInfo = (data) => {
    if (data) {
      name.value = data.name || data.username || ''
      avatar.value = data.avatar || ''
      roles.value = Array.isArray(data.roles) ? data.roles : []
      userInfo.value = data

      // 如果有token，也保存token
      if (data.token) {
        setToken(data.token)
      }
    }
  }

  const loginAction = async (loginData) => {
    try {
      const res = await login(loginData)
      if (res.code === 200) {
        // 获取token和用户信息
        const token = res.data?.token
        const name = res.data?.name

        if (token) {
          setToken(token)
          // 设置基本用户信息
          setUserInfo({
            name: name,
            username: name,
            token: token
          })

          // 尝试获取完整用户信息
          try {
            await getUserInfo()
          } catch (error) {
            console.warn('获取完整用户信息失败，使用基本信息:', error)
          }
        } else {
          throw new Error('登录失败：未获取到token')
        }
      } else {
        throw new Error(res.msg || '登录失败')
      }
      return res
    } catch (error) {
      clearToken()
      throw error
    }
  }

  const getUserInfo = async () => {
    if (!token.value) {
      return null
    }

    try {
      const res = await getInfo()
      if (res.code === 200) {
        const data = res.data || res
        name.value = data.name || data.username || ''
        avatar.value = data.avatar || ''
        roles.value = Array.isArray(data.roles) ? data.roles : ['admin']
        userInfo.value = data
        return data
      }
      return null
    } catch (error) {
      console.warn('获取用户信息失败:', error)
      // 不清除token，因为可能只是网络问题
      return null
    }
  }

  const logoutAction = async () => {
    try {
      if (token.value) {
        await logout()
      }
    } finally {
      clearToken()
      name.value = ''
      avatar.value = ''
      roles.value = []
      userInfo.value = null
    }
  }

  return {
    token,
    name,
    avatar,
    roles,
    userInfo,
    setToken,
    clearToken,
    setUserInfo,
    loginAction,
    getUserInfo,
    logoutAction
  }
}) 